//
//  MailViewController.m
//  GroupManager
//
//  Created by 欧阳 鹏 on 11-10-28.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MailViewController.h"
#import "GMPerson.h"


@implementation MailViewController

@synthesize group;


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	if (!dict) {
		dict = [[NSMutableDictionary alloc] init];
	}
	if (!keys) {
		keys = [[NSMutableArray alloc] init];
	}
	for (GMPerson *person in group.persons) {
		ABMutableMultiValueRef mailArrRef = ABRecordCopyValue(person.person, kABPersonEmailProperty);
		NSMutableArray *arr = [[NSMutableArray alloc] init];
		for (int i = 0; i < ABMultiValueGetCount(mailArrRef); i ++) {
			NSString *label = [(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(mailArrRef, i)) autorelease];
			NSString *mail = [(NSString*)ABMultiValueCopyValueAtIndex(mailArrRef, i) autorelease];
			[arr addObject:[NSMutableArray arrayWithObjects:label, mail, [NSNumber numberWithBool:YES], nil]];
			NSLog(@"%@", mail);
		}
		if ([arr count]) {
			NSString *name = [(NSString*)ABRecordCopyCompositeName(person.person) autorelease];
			NSLog(@"%@", name);
			[keys addObject:name];
			[dict setObject:arr forKey:name];
		}
		[arr release];
		CFRelease(mailArrRef);
	}
	
	UIBarButtonItem *sendButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"send", nil)
																   style:UIBarButtonItemStylePlain target:self action:@selector(send)];
	self.navigationItem.rightBarButtonItem = sendButton;
	[sendButton release];
	
	if ([keys count] == 0) {
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
		label.center = CGPointMake(160, 240);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
		label.textColor = [UIColor lightGrayColor];
		label.text = NSLocalizedString(@"there is no email address", nil);
		[self.tableView addSubview:label];
		[label release];
	}
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


/*
 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
 }
 */
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [keys count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	NSString *key = [keys objectAtIndex:section];
	NSArray *arr = [dict valueForKey:key];
    return [arr count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	NSString *key = [keys objectAtIndex:indexPath.section];
	NSArray *arr = [dict valueForKey:key];
	cell.accessoryType = [[[arr objectAtIndex:indexPath.row] objectAtIndex:2] boolValue] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
	cell.textLabel.text = [[arr objectAtIndex:indexPath.row] objectAtIndex:0];
	cell.detailTextLabel.text = [[arr objectAtIndex:indexPath.row] objectAtIndex:1];
	
    return cell;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [keys objectAtIndex:section];
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
	 // ...
	 // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	cell.accessoryType = (cell.accessoryType == UITableViewCellAccessoryCheckmark) ? UITableViewCellAccessoryNone : UITableViewCellAccessoryCheckmark;
	NSString *key = [keys objectAtIndex:indexPath.section];
	NSArray *arr = [dict valueForKey:key];
	NSMutableArray *valArr = [arr objectAtIndex:indexPath.row];
	[valArr replaceObjectAtIndex:2 withObject:[NSNumber numberWithInt:cell.accessoryType]];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[dict release];
	[keys release];
    [super dealloc];
}

#pragma mark -
#pragma mark MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	[controller dismissModalViewControllerAnimated:YES];
}

- (void)send {
	MFMailComposeViewController *c = [[MFMailComposeViewController alloc] init];
	NSMutableArray *mailArr = [[NSMutableArray alloc] init];
	for (NSString *key in keys) {
		NSArray *arr = [dict valueForKey:key];
		for (NSArray *valArr in arr) {
			if ([[valArr objectAtIndex:2] boolValue]) {
				[mailArr addObject:[valArr objectAtIndex:1]];
			}
		}
	}
	c.mailComposeDelegate = self;
	[c setToRecipients:mailArr];
	[mailArr release];
	[self presentModalViewController:c animated:YES];
	[c release];
}


@end

